import {
  Button,
  Checkbox,
  CheckboxGroup,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Radio,
  RadioGroup,
  RangePicker,
  Select,
  SelectOption,
  Space,
  Spin
} from 'ant-design-vue'
import { cond } from 'lodash-es'
import moment, { Moment } from 'moment'
import {
  defineComponent,
  onActivated,
  onDeactivated,
  onMounted,
  ref
} from 'vue'
import { useRoute } from 'vue-router'

import { commonApi, couponApi } from '@/apis'
import jdCouponApi from '@/apis/jdCouponApi'
import { JdCouponItem } from '@/apis/jdCouponTypes'
import { ProEditor, ProEditorProps, ProEditorRef } from '@/components'
import { useBack } from '@/hooks'
import CinemaSelectList from '@/views/movie/timeLimitManage/createLimit/hook/cinemaSelectList'
import MovieList from '@/views/movie/timeLimitManage/createLimit/hook/movieList'
import {
  brandIdOptions,
  cinemaTypeOptions,
  couponTypeOptions,
  dimensionMovieOptions,
  dimensionOptions,
  restaurantTypeOptions,
  sceneTypeOptions
} from '@/views/order/constants'
import ProductList from '@/views/order/timeLimitManage/createLimit/hook/productList'
import ShopSelectList from '@/views/order/timeLimitManage/createLimit/hook/shopSelectList'

import JdgGoodsSelectList from './hook/jdgGoodsSelectList'
import JdlGoodsSelectList from './hook/jdlGoodsSelectList'
import SiteSelectList from './hook/siteSelectList'

export default defineComponent({
  name: 'JdCouponCreateLimit',
  setup() {
    const loading = ref(false)
    const { handleCancel } = useBack('refreshTimeLimitList')
    const route = useRoute()
    const activityData = ref({} as JdCouponItem)

    const selectTime = ref([] as any[])
    const diffViewShow = ref(true)
    const submitLoading = ref(false)
    const editorRef = ref({} as ProEditorRef)
    const editorConfig = ref({
      wrapStyle: {
        width: '702px'
      },
      editorStyle: {
        height: '300px'
      },
      editorHtml: '',
      editorVisible: false,
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: commonApi.uploadFileUrl,
            fieldName: 'file',
            customInsert(res: any, insertFn: any) {
              // res 即服务端的返回结果
              const url = res.data

              // 从 res 中找到 url alt href ，然后插图图片
              insertFn(url, '', '')
            }
          }
        } as any
      },
      toolbarConfig: {
        excludeKeys: ['group-video']
      }
    } as ProEditorProps)

    const disabledDate = (current: Moment) => {
      return current && current < moment().startOf('day')
    }

    onMounted(() => {
      if (route.query.id) {
        getDetail()
      } else {
        activityData.value.couponType = 4
        activityData.value.brandIds = []
        activityData.value.status = 1
        activityData.value.storeType = 0
        activityData.value.useDimesion = 0
        activityData.value.storeCommandList = []
        activityData.value.productCommandList = []
        editorConfig.value.editorVisible = true
      }
    })

    //获取详情
    async function getDetail() {
      try {
        loading.value = true

        activityData.value = await jdCouponApi.getJdCouponDetail(route.query.id)
        //赋值
        if (
          activityData.value.type == 1 &&
          activityData.value.storeCommandList
        ) {
          restaurantList.value = activityData.value.storeCommandList.map(
            item => {
              return {
                id: item.storeId,
                restaurantName: item.storeName
              }
            }
          )
        }
        if (
          activityData.value.type == 2 &&
          activityData.value.storeCommandList
        ) {
          cinemaList.value = activityData.value.storeCommandList.map(item => {
            return {
              id: item.storeId,
              cinemaName: item.storeName
            }
          })
        }
        selectTime.value = activityData.value.startTime
          ? [
              moment(activityData.value.startTime),
              moment(activityData.value.endTime)
            ]
          : []
        editorConfig.value.editorHtml = activityData.value.couponDesc
        editorConfig.value.editorVisible = true
      } finally {
        loading.value = false
      }
    }

    //创建优惠券
    async function handleCreateActivity() {
      for (const i in activityData.value) {
        try {
          activityData.value[i] = activityData.value[i].trim()
        } catch {}
      }

      if (!activityData.value.name) {
        message.warning('请输入卡片名称')
        return
      }
      if (!activityData.value.type) {
        message.warning('请选择可用场景')
        return
      }
      if (activityData.value.type == 1) {
        if (activityData.value.brandIds.length == 0) {
          message.warning('请选择可用品牌')
          return
        }
        if (
          activityData.value.useDimesion == 0 &&
          activityData.value.storeType == 1 &&
          activityData.value.storeCommandList.length == 0
        ) {
          message.warning('请选择门店')
          return
        }
        if (
          activityData.value.useDimesion == 1 &&
          activityData.value.productCommandList.length == 0
        ) {
          message.warning('请导入商品')
          return
        }
      } else if (activityData.value.type == 2) {
        if (
          activityData.value.useDimesion == 0 &&
          activityData.value.storeType == 1 &&
          activityData.value.storeCommandList.length == 0
        ) {
          message.warning('请选择影院')
          return
        }
        if (
          activityData.value.useDimesion == 1 &&
          activityData.value.productCommandList.length == 0
        ) {
          message.warning('请导入电影')
          return
        }
      } else if (activityData.value.type == 9) {
        if (
          activityData.value.useDimesion == 0 &&
          activityData.value.storeType == 1 &&
          activityData.value.storeCommandList.length == 0
        ) {
          message.warning('请选择站点')
          return
        }
        if (
          activityData.value.useDimesion == 1 &&
          activityData.value.storeType == 1 &&
          activityData.value.productCommandList.length == 0
        ) {
          message.warning('请选择商品')
          return
        }
      } else if (activityData.value.type == 10) {
        if (
          activityData.value.storeType == 1 &&
          activityData.value.productCommandList.length == 0
        ) {
          message.warning('请选择商品')
          return
        }
      } else {
        if (activityData.value.rechargeType.length == 0) {
          message.warning('请选择充值类型')
          return
        }
        if (activityData.value.rechargeAmountNames.length == 0) {
          message.warning('请选充值档位')
          return
        }
      }
      if (activityData.value.couponType != 3 && !activityData.value.discount) {
        message.warning('请输入折扣')
        return
      }
      if (!activityData.value.quantity) {
        message.warning('请输入发放数量')
        return
      }
      //赋值
      activityData.value.startTime =
        selectTime.value.length > 0 ? selectTime.value[0].format('x') : ''
      activityData.value.endTime =
        selectTime.value.length > 1 ? selectTime.value[1].format('x') : ''
      activityData.value.couponDesc = editorRef.value.editor.getHtml()
      try {
        submitLoading.value = true
        if (route.query.id) {
          await jdCouponApi.editJdCoupon(activityData.value)
        } else {
          await jdCouponApi.createJdCoupon(activityData.value)
        }
        handleCancel()
      } finally {
        submitLoading.value = false
      }
    }

    //切换场景
    function handleSceneChange() {
      activityData.value.useDimesion = 0
      if (activityData.value.type == 10) {
        activityData.value.useDimesion = 1
      }
      activityData.value.storeType = 0
      activityData.value.storeCommandList = []
      activityData.value.productCommandList = []
      activityData.value.rechargeType = []
      activityData.value.rechargeAmountNames = []
    }

    //大盘点餐相关
    const restaurantList = ref([] as any[])
    const productUploadList = ref([] as any[])
    const shopSelectList = ref<ComponentRef>({})
    const productList = ref<ComponentRef>({})
    /** 维度变化 */
    function handleDimensionChange() {
      activityData.value.storeCommandList = []
      restaurantList.value = []
      activityData.value.productCommandList = []
      productUploadList.value = []

      cinemaList.value = []
      movieUploadList.value = []
    }
    /** 供应商改变刷新地区、门店列表 */
    function handleBrandChange() {
      activityData.value.useDimesion = 0
      activityData.value.storeType = 0
      handleClearProduct()
      handleClearRestaurant()
    }
    /** 选择门店 */
    function handleShopSelect(val) {
      activityData.value.storeCommandList = val?.map(item => {
        return {
          storeId: item.id,
          storeName: item.restaurantName
        }
      })
    }
    /** 上传商品 */
    function handleProductCallback(val) {
      activityData.value.productCommandList = val
    }
    /** 选择变更清空门店 */
    function handleClearRestaurant() {
      activityData.value.storeCommandList = []
      restaurantList.value = []
    }
    /** 清空商品 */
    function handleClearProduct() {
      activityData.value.productCommandList = []
      productUploadList.value = []
    }

    //看电影相关
    const movieUploadList = ref([] as any[])
    const cinemaList = ref([] as any[])
    /** 选择影院 */
    function handleCinemaSelect(val) {
      activityData.value.storeCommandList = val?.map(item => {
        return {
          storeId: item.id,
          storeName: item.cinemaName
        }
      })
    }
    /** 上传电影 */
    function handleMovieCallback(val) {
      activityData.value.productCommandList = val?.map(item => {
        return {
          productId: item.movieId,
          productName: item.movieName
        }
      })
    }

    //充值相关
    const rechargeType = {
      3: [
        { label: '普通慢充', value: 3 },
        { label: '普通快充', value: 5 },
        { label: '优质快充', value: 6 },
        { label: '话费速充', value: 4 }
      ],
      4: [
        { label: '国网电力公司', value: 1 },
        { label: '南网电力公司', value: 2 }
      ],
      5: [
        { label: 'VIP', value: 1 },
        { label: '超级影视', value: 2 }
      ],
      6: [
        { label: '黄金会员', value: 1 },
        { label: '星钻VIP', value: 2 },
        { label: '白金会员', value: 3 },
        { label: '京东PLUS联名', value: 4 }
      ],
      7: [
        { label: '会员', value: 1 },
        { label: '全屏会员', value: 2 }
      ],
      8: [
        { label: 'VIP', value: 1 },
        { label: '酷喵VIP', value: 2 }
      ]
    }
    const rechargeLevel = {
      3: [
        { label: '50元', value: '50' },
        { label: '100元', value: '100' },
        { label: '200元', value: '200' }
      ],
      4: [
        { label: '100元', value: '100' },
        { label: '200元', value: '200' },
        { label: '300元', value: '300' },
        { label: '400元', value: '400' },
        { label: '500元', value: '500' },
        { label: '600元', value: '600' },
        { label: '800元', value: '800' },
        { label: '1000元', value: '1000' }
      ],
      5: [
        { label: '1个月', value: '1个月' },
        { label: '3个月', value: '3个月' },
        { label: '12个月', value: '12个月' }
      ],
      6: [
        { label: '1个月', value: '1个月' },
        { label: '3个月', value: '3个月' },
        { label: '6个月', value: '6个月' },
        { label: '12个月', value: '12个月' }
      ],
      7: [
        { label: '7天', value: '7天' },
        { label: '1个月', value: '1个月' },
        { label: '3个月', value: '3个月' },
        { label: '6个月', value: '6个月' },
        { label: '12个月', value: '12个月' }
      ],
      8: [
        { label: '周卡', value: '周卡' },
        { label: '1个月', value: '1个月' },
        { label: '3个月', value: '3个月' },
        { label: '12个月', value: '12个月' }
      ]
    }

    return {
      loading,
      restaurantList,
      activityData,
      selectTime,
      cinemaList,
      rechargeType,
      rechargeLevel,
      shopSelectList,
      editorRef,
      editorConfig,
      diffViewShow,
      submitLoading,
      productList,

      disabledDate,
      handleCancel,
      handleShopSelect,
      handleDimensionChange,
      handleProductCallback,
      handleBrandChange,
      handleCinemaSelect,
      handleMovieCallback,
      handleSceneChange,
      handleCreateActivity
    }
  },
  render() {
    let diffView
    if (this.activityData.type) {
      switch (this.activityData.type) {
        //大盘点餐
        case 1:
          diffView = (
            <div>
              <FormItem label="可用品牌" required>
                <CheckboxGroup
                  v-model:value={this.activityData.brandIds}
                  onChange={this.handleBrandChange}
                >
                  {brandIdOptions.map(val => (
                    <Checkbox value={val.value}>{val.label}</Checkbox>
                  ))}
                </CheckboxGroup>
              </FormItem>
              <FormItem
                label="可用维度"
                v-show={this.activityData.brandIds?.length > 0}
                required
              >
                <RadioGroup
                  v-model:value={this.activityData.useDimesion}
                  onChange={this.handleDimensionChange}
                >
                  {this.activityData.brandIds?.length > 1 ? (
                    <div>全部门店和商品</div>
                  ) : (
                    dimensionOptions.map(val => (
                      <Radio value={val.value}>{val.label}</Radio>
                    ))
                  )}
                </RadioGroup>
              </FormItem>
              <div v-show={this.activityData.brandIds?.length == 1}>
                {this.activityData.useDimesion == 0 ? (
                  <div style={{ marginLeft: '8.35%' }}>
                    <FormItem>
                      <RadioGroup v-model:value={this.activityData.storeType}>
                        {restaurantTypeOptions.map(val => (
                          <Radio value={val.value}>{val.label}</Radio>
                        ))}
                      </RadioGroup>
                    </FormItem>
                    <FormItem v-show={this.activityData.storeType == 1}>
                      <ShopSelectList
                        ref="shopSelectList"
                        restaurants={this.restaurantList}
                        onlyId={false}
                        brandId={this.activityData.brandIds[0] ?? 0}
                        province={''}
                        city={''}
                        onDataCallback={this.handleShopSelect}
                      />
                    </FormItem>
                  </div>
                ) : (
                  <div style={{ marginLeft: '8.35%' }}>
                    <FormItem>
                      <ProductList
                        ref="productList"
                        brandId={this.activityData.brandIds[0] ?? 0}
                        onDataCallback={this.handleProductCallback}
                      />
                    </FormItem>
                  </div>
                )}
              </div>
            </div>
          )
          break
        //看电影
        case 2:
          diffView = (
            <div>
              <FormItem label="可用维度">
                <RadioGroup
                  v-model:value={this.activityData.useDimesion}
                  onChange={this.handleDimensionChange}
                >
                  {dimensionMovieOptions.map(val => (
                    <Radio value={val.value}>{val.label}</Radio>
                  ))}
                </RadioGroup>
              </FormItem>
              {this.activityData.useDimesion == 0 ? (
                <div style={{ marginLeft: '8.35%' }}>
                  <FormItem>
                    <RadioGroup v-model:value={this.activityData.storeType}>
                      {cinemaTypeOptions.map(val => (
                        <Radio value={val.value}>{val.label}</Radio>
                      ))}
                    </RadioGroup>
                  </FormItem>
                  <FormItem v-show={this.activityData.storeType == 1}>
                    <CinemaSelectList
                      ref="cinemaSelectList"
                      cinemas={this.cinemaList}
                      province={''}
                      onlyId={false}
                      city={''}
                      onDataCallback={this.handleCinemaSelect}
                    />
                  </FormItem>
                </div>
              ) : (
                <div style={{ marginLeft: '8.35%' }}>
                  <FormItem>
                    <MovieList
                      ref="movieList"
                      onDataCallback={this.handleMovieCallback}
                    />
                  </FormItem>
                </div>
              )}
            </div>
          )
          break
        //充值
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
          diffView = (
            <div>
              <FormItem label="充值类型" required>
                <CheckboxGroup
                  v-model={[this.activityData.rechargeType, 'value']}
                >
                  {this.rechargeType[this.activityData.type].map(item => {
                    return <Checkbox value={item.value}>{item.label}</Checkbox>
                  })}
                </CheckboxGroup>
              </FormItem>
              <FormItem label="充值档位" required>
                <CheckboxGroup
                  v-model={[this.activityData.rechargeAmountNames, 'value']}
                >
                  {this.rechargeLevel[this.activityData.type].map(item => {
                    return <Checkbox value={item.value}>{item.label}</Checkbox>
                  })}
                </CheckboxGroup>
              </FormItem>
            </div>
          )
          break
        //金豆惠生活
        case 9:
          diffView = (
            <div>
              <FormItem label="可用维度" required>
                <Space direction="vertical">
                  <RadioGroup v-model:value={this.activityData.useDimesion}>
                    <Radio value={0}>{'站点'}</Radio>
                    <Radio value={1}>{'商品'}</Radio>
                  </RadioGroup>
                  <Space direction="vertical">
                    <RadioGroup v-model:value={this.activityData.storeType}>
                      <Radio value={0}>
                        {this.activityData.useDimesion == 0
                          ? '全部站点'
                          : '全部商品'}
                      </Radio>
                      <Radio value={1}>
                        {this.activityData.useDimesion == 0
                          ? '指定站点'
                          : '指定商品'}
                      </Radio>
                    </RadioGroup>
                    {this.activityData.useDimesion == 0 &&
                    this.activityData.storeType == 1 ? (
                      <SiteSelectList
                        sites={this.activityData.storeCommandList}
                        onDataCallback={sites => {
                          this.activityData.storeCommandList = sites
                        }}
                      ></SiteSelectList>
                    ) : null}
                    {this.activityData.useDimesion == 1 &&
                    this.activityData.storeType == 1 ? (
                      <JdlGoodsSelectList
                        jdlGoods={this.activityData.productCommandList}
                        onDataCallback={goods => {
                          this.activityData.productCommandList = goods
                        }}
                      ></JdlGoodsSelectList>
                    ) : null}
                  </Space>
                </Space>
              </FormItem>
            </div>
          )
          break
        //金豆兑好礼
        case 10:
          diffView = (
            <div>
              <FormItem label="可用维度" required>
                <Space direction="vertical">
                  <RadioGroup v-model:value={this.activityData.storeType}>
                    <Radio value={0}>{'全部商品'}</Radio>
                    <Radio value={1}>{'指定商品'}</Radio>
                  </RadioGroup>
                  {this.activityData.storeType == 1 ? (
                    <JdgGoodsSelectList
                      jdgGoods={this.activityData.productCommandList}
                      onDataCallback={goods => {
                        this.activityData.productCommandList = goods
                      }}
                    ></JdgGoodsSelectList>
                  ) : null}
                </Space>
              </FormItem>
            </div>
          )
          break
      }
    }

    return (
      <div>
        <Spin spinning={this.loading}>
          <h3 style={{ marginLeft: '30px' }}>
            {this.$route.query.id ? '编辑抵扣卷' : '新增抵扣券'}
          </h3>
          <Form labelCol={{ span: 2 }}>
            <FormItem label="卡片名称：" required>
              <Input
                maxlength={60}
                v-model:value={this.activityData.name}
                placeholder="请输入"
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="可用场景：" required>
              <Select
                v-model:value={this.activityData.type}
                placeholder="请选择"
                onChange={this.handleSceneChange}
                style={{ width: '300px' }}
              >
                {sceneTypeOptions.map(val => (
                  <SelectOption value={val.value}>{val.label}</SelectOption>
                ))}
              </Select>
            </FormItem>
            <div v-show={this.diffViewShow}>{diffView}</div>
            <FormItem label="折扣类型：" required>
              <RadioGroup v-model:value={this.activityData.couponType}>
                {couponTypeOptions.map(val => (
                  <Radio value={val.value}>{val.label}</Radio>
                ))}
              </RadioGroup>
            </FormItem>
            <FormItem
              label=" "
              colon={false}
              v-show={this.activityData.couponType != 3}
            >
              <InputNumber
                v-model:value={this.activityData.discount}
                placeholder="请输入折扣"
                min={0}
                max={10}
                precision={2}
                style={{ width: '300px' }}
              />
              {` 折`}
            </FormItem>
            <FormItem label="可发放数量：" required>
              <InputNumber
                placeholder="请输入"
                v-model:value={this.activityData.quantity}
                min={0}
                precision={0}
                maxlength={8}
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="卡片使用说明：">
              <ProEditor ref="editorRef" {...this.editorConfig} />
            </FormItem>
            <FormItem label="卡片有效期：">
              <RangePicker
                disabledDate={this.disabledDate}
                v-model:value={this.selectTime}
                showTime={{
                  hideDisabledOptions: true,
                  defaultValue: [
                    moment('00:00:00', 'HH:mm:ss'),
                    moment('23:59:59', 'HH:mm:ss')
                  ]
                }}
                format={'YYYY-MM-DD HH:mm:ss'}
                separator={'至'}
                style={{ width: '400px' }}
              />
            </FormItem>

            <FormItem label="状态：" required>
              <RadioGroup v-model:value={this.activityData.status}>
                <Radio value={1}>启用</Radio>
                <Radio value={0}>禁用</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem>
              <Button
                style={{ marginTop: '30px', marginLeft: '90px' }}
                onClick={this.handleCancel}
              >
                取消
              </Button>
              <Button
                type="primary"
                loading={this.submitLoading}
                style={{ marginTop: '30px', marginLeft: '90px' }}
                onClick={this.handleCreateActivity}
              >
                确定
              </Button>
            </FormItem>
          </Form>
        </Spin>
      </div>
    )
  }
})
